package jh.com.jhappbf.dispatchcar;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbDialogFragment.AbDialogOnLoadListener;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.util.AbDialogUtil;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.model.ContractSettingModel;
import jh.com.jhappbf.model.PlanModel;
import jh.com.jhappbf.ui.State;
import jh.com.jhappbf.utils.JsonHelper;

public class DispatchContractSelect extends AbActivity {
	private View mContentView;
	private View mErrorView;
	private Context mAppContext;
	private LinearLayout mHeaderLayout;
	private ListView mListView;
	private Button mTryAgin;
	private List<JSONObject> mData;
	private Button mTitleRightBtn;
	private List<String> mHeaderTitle;
	private Drawable mLeftDrawable;
	private int mColumnWidth;
	private AbLoadDialogFragment mDialogFragment = null;
	private myBaseAdapter mAdapter;
	private ContractSettingModel mSettingModel;
	private final int GETSETTING = 0X0001;
	private String mType ;
	private Button queryBtn;
	private EditText mInputEdit;
	private ImageView mInputClear;
	private Button commit;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContentView = getLayoutInflater().inflate(
				R.layout.contract_select_activity, null);
		mErrorView = getLayoutInflater().inflate(R.layout.net_error_activity,
				null);
		setAbContentView(mContentView);
		Intent i = getIntent();
		mType = i.getStringExtra("type");
		mSettingModel  = i .getParcelableExtra("setting");
		
		AbTitleBar mAbTitleBar = this.getTitleBar();
		mAbTitleBar.setTitleText("合同选择");
		mAbTitleBar.setLogo(R.drawable.button_selector_back);
		mAbTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));
		mAbTitleBar.setTitleTextMargin(10, 0, 0, 0);
		mAbTitleBar.setLogoLine(R.mipmap.line);
		mAbTitleBar.setLogoOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent();
				i.putExtra("result", mSettingModel);
				setResult(RESULT_OK, i);
				DispatchContractSelect.this.finish();
			}
		});
		View rightViewMore = mInflater.inflate(
				R.layout.title_right_app_btn_view, null);
		mAbTitleBar.addRightView(rightViewMore);
		mTitleRightBtn = (Button) rightViewMore.findViewById(R.id.title_right_btn);
		initView();
	}
	
		/**
		 * 初始化
		 */
		private void initView() {
			mAppContext = getApplicationContext();
			mHeaderLayout = (LinearLayout) mContentView
					.findViewById(R.id.contract_select_title);
			commit=mContentView.findViewById(R.id.commit);
			commit.setOnClickListener(v -> {
				    if (mSelectRight.size()>0){
				    	String planId="";
				    	String cargoname="";
				    	String sender="";
				    	String reciver="";
				    	String price="";
						String unit="";
						String span="";
						for (int i = 0; i < mSelectRight.size(); i++) {
							try {
								JSONObject object =new JSONObject(mSelectRight.get(i));
								if (i==0){
									planId+=object.optString("计划单号");
									cargoname+=object.optString("货名");
									sender+=object.optString("发货");
									reciver+=object.optString("收货");
									price+=object.optString("单价");
									unit+=object.optString("单位");
									span+=object.optString("规格");

								}else {
									planId+=","+object.optString("计划单号");
									cargoname+=","+object.optString("货名");
									sender+=","+object.optString("发货");
									reciver+=","+object.optString("收货");
									price+=","+object.optString("单价");
									unit+=","+object.optString("单位");
									span+=","+object.optString("规格");
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
						PlanModel model = new PlanModel();
						model.setPlanId(planId);
						model.setCargoname(cargoname);
						model.setSender(sender);
						model.setReceiver(reciver);
						model.setPrice(price);
						model.setUnit(unit);
						model.setSpec(span);
						Intent i1 = new Intent();
						i1.putExtra("plan", model);
						DispatchContractSelect.this.setResult(RESULT_OK, i1);
						DispatchContractSelect.this.finish();
					}

			});
			mListView = (ListView) mContentView
					.findViewById(R.id.contract_select_listView);
			mAdapter =new myBaseAdapter();
			mData = new ArrayList<JSONObject>();
			mListView.setAdapter(mAdapter);
			mTryAgin = (Button) mErrorView.findViewById(R.id.network_error_btn);
			mHeaderTitle = new ArrayList<String>();
			mLeftDrawable = getResources().getDrawable(R.drawable.table_line);
			mLeftDrawable.setBounds(0, 0, mLeftDrawable.getMinimumWidth(),
					mLeftDrawable.getMinimumHeight());
			mColumnWidth = (int) TypedValue.applyDimension(
					TypedValue.COMPLEX_UNIT_DIP, 55, getResources()
							.getDisplayMetrics());
			mTryAgin.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					setAbContentView(mContentView);
					refresh();
				}
			});
			queryBtn= (Button) findViewById(R.id.query_btn);
			queryBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View view) {
					refresh();
				}
			});
			mInputEdit = (EditText) findViewById(R.id.select_edit);
			mInputClear = (ImageView) findViewById(R.id.select_clear);
			mInputEdit.addTextChangedListener(new TextWatcher() {
				@Override
				public void onTextChanged(CharSequence s, int start, int before,
                                          int count) {
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start, int count,
                                              int after) {

				}

				@Override
				public void afterTextChanged(Editable s) {
					if (s.toString().length() == 0) {
						mInputClear.setVisibility(View.GONE);
					} else {
						mInputClear.setVisibility(View.VISIBLE);
					}
				}
			});
			mInputClear.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View view) {
					mInputEdit.setText("");
				}
			});

			mTitleRightBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent i  = new Intent(DispatchContractSelect.this,ContractSelectSetting.class);
					i.putExtra("flag", "input");
					i.putExtra("mType", mType);
					i.putExtra("setting", mSettingModel);
					startActivityForResult(i, GETSETTING);
				}
			});

			mListView.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {

					CheckBox chk = (CheckBox) view
							.findViewById(R.id.list_view_item_check);
					String right = mData.get(position).toString();
					if (chk.isChecked()) {
						chk.setChecked(false);
						if (mSelectRight.contains(right)) {
							mSelectRight.remove(right);
							map.put(position,false);
						}
					} else {
						chk.setChecked(true);
						if (!mSelectRight.contains(right)) {
							mSelectRight.add(right);
							map.put(position,true);
						}
					}
				}
			});
			refresh();
		}
		
		@Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			super.onActivityResult(requestCode, resultCode, data);
			if(data != null && requestCode == GETSETTING)
			{
				mSettingModel = data.getParcelableExtra("result");
				if(mSettingModel != null)
				{
					refresh();
				}
			}
		}
		
		// /刷新
		private void refresh() {
			mDialogFragment = AbDialogUtil.showLoadDialog(DispatchContractSelect.this,
					R.drawable.ic_load, "查询中,请稍等...");
			mDialogFragment.setCancelable(false);
			mDialogFragment.setAbDialogOnLoadListener(new AbDialogOnLoadListener() {

				@Override
				public void onLoad() {
					getData(mSettingModel);
				}
			});
		}

		// /获取数据
		private void getData(ContractSettingModel model) {
//			String methodName = "getCargonameContract";
			String methodName = "getPlan";
			ArrayList<String> param = new ArrayList<String>();
			ArrayList<String> value = new ArrayList<String>();
			param.add("startTime");
			param.add("endTime");
			param.add("company");
			param.add("spec");
			param.add("cargoname");
			param.add("sender");
			param.add("receiver");
			param.add("type");
			param.add("like");


			
			if (model == null) {
				Date date = new Date();
				String end = "";
				String start ="";
				value.add(start);
				value.add(end);
				value.add(State.mCompanyName);
				value.add("");
				value.add("");
				value.add("");
				value.add("");
				value.add(mType);
				value.add(mInputEdit.getText().toString().trim());


			} else {
				value.add(model.getStartTime());
				value.add(model.getEndTime());
				value.add(State.mCompanyName);
				value.add(model.getSpec());
				value.add(model.getCargoname());
				value.add(model.getSender());
				value.add(model.getReceiver());
				value.add(mType);
				value.add(mInputEdit.getText().toString().trim());

			}

			Listener<String> listener = new Listener<String>() {

				@Override
				public void onResponse(String response) {

					AbDialogUtil.removeDialog(DispatchContractSelect.this);
					if (mDialogFragment != null)
						mDialogFragment.dismiss();

					List<JSONObject> newListData = JsonHelper
							.getJsonObjects(response);
					if (newListData != null) {
						mHeaderTitle = new ArrayList<String>();
						if(newListData.size() > 0)
						{
							String[] head = newListData.get(0).optString("alias").split(",");
							mHeaderTitle = Arrays.asList(head);
//							makeHead();
						}
						mData.clear();
						mData.addAll(newListData);
						mAdapter.notifyDataSetChanged();
					}
				}
			};

			ErrorListener errorListener = new ErrorListener() {
				@Override
				public void onErrorResponse(VolleyError error) {
					AbDialogUtil.removeDialog(DispatchContractSelect.this);
					if (mDialogFragment != null)
						mDialogFragment.dismiss();
					setAbContentView(mErrorView);
					mData.clear();
					mAdapter.notifyDataSetChanged();
				}
			};

			VolleyCallWebService webService = new VolleyCallWebService(methodName,
					param, value, listener, errorListener, Priority.NORMAL);
			VolleySingleton.getVolleyInstance(mAppContext).addRequest(webService);
		}

		// 生成表头
		private void makeHead() {
			mHeaderLayout.removeAllViews();
			for (int index = 0; index < mHeaderTitle.size(); index++) {
				TextView txt = new TextView(DispatchContractSelect.this);
				if("发货".equals(mHeaderTitle.get(index)) 
						|| "收货".equals(mHeaderTitle.get(index))||
						"单位".equals(mHeaderTitle.get(index)))
				{
					txt.setWidth((int)(mColumnWidth*2.5));
				} else if("计划单号".equals(mHeaderTitle.get(index)) || "货名".equals(mHeaderTitle.get(index)))
				{
					txt.setWidth((int)(mColumnWidth*1.5));
				}
				else {
					txt.setWidth((int) (mColumnWidth*1.5));
				}
				
				txt.setTextColor(Color.BLACK);
				txt.setGravity(Gravity.CENTER);
				txt.setCompoundDrawables(mLeftDrawable, null, null, null);
				txt.setPadding(1, 0, 1, 0);
				txt.setId(index);
				txt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
				txt.setText(mHeaderTitle.get(index));
				mHeaderLayout.addView(txt);
			}
		}


	class myBaseAdapter extends BaseAdapter
	{
		@Override
		public int getCount() {
			return mData.size();
		}

		@Override
		public Object getItem(int position) {
			return mData.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			final int index=position;
			if(convertView == null)
			{
				holder = new ViewHolder();
				LayoutInflater inflater =  (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
				convertView = inflater.inflate(R.layout.contract_query_list_item, null);
				holder.plateNumber = (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_platenum);
				holder.cargoname  = (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_cargoname);
				holder.states= (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_state);
				holder.stime = (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_times);
				holder.guige = (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_guige);
//				holder.span = (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_span);
				holder.price = (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_price);
				holder.leiji = (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_leiji);
				holder.type = (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_type);
//				holder.plannum = (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_plannum);
				holder.checkBox=convertView.findViewById(R.id.list_view_item_check);
				convertView.setTag(holder);
				holder.checkBox.setTag(index);
			}
			else
			{
				holder = (ViewHolder) convertView.getTag();
			}
			JSONObject object= mData.get(position);
			String planIdNum=object.toString();
			holder.plateNumber.setText("计划单号: "+object.optString("计划单号"));
			holder.cargoname.setText("货名: "+object.optString("货名"));
			holder.guige.setText("收货: "+object.optString("收货"));
			holder.price.setText("单价: "+object.optString("单价"));
			holder.leiji.setText("累计量: "+object.optString("累计量"));
			holder.plannum.setText("计划量: "+object.optString("计划量"));
			holder.stime.setText("单位: "+object.optString("单位"));
			holder.states.setText("发货: "+object.optString("发货"));
			holder.span.setText("规格: "+object.optString("规格"));
			holder.type.setText("类型:"+mType);
			if (mSelectRight.contains(planIdNum)) {
				holder.checkBox.setChecked(true);
			} else {
				holder.checkBox.setChecked(false);
				if (mSelectRight.contains(planIdNum)) {
					mSelectRight.remove(planIdNum);
				}
			}
			return convertView;
		}
	}
	private List<String> mSelectRight=new ArrayList<String>();
	private Map<Integer,Boolean> map =new HashMap<Integer, Boolean>();
	class ViewHolder
	{
		public String id ;
		public ImageView img;
		public TextView plateNumber;
		public TextView cargoname;
		public TextView states;
		public TextView stime;
		public TextView guige;
		public TextView price;
		public TextView leiji;
		public TextView type;
		public TextView plannum;
		public TextView span;
		public CheckBox checkBox;


	}

	class CollectBaseAdapter extends BaseAdapter {
		@Override
		public int getCount() {
			return mData.size();
		}

		@Override
		public Object getItem(int position) {
			return mData.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@SuppressLint("NewApi")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TableLayout tableLayout = null;
			if (convertView == null) {
				tableLayout = new TableLayout(DispatchContractSelect.this);
				TableRow tableRow = new TableRow(DispatchContractSelect.this);
				Drawable mItemSelect = getResources().getDrawable(
						R.drawable.list_item_bg);
				tableRow.setBackground(mItemSelect);
				tableRow.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
				for (int index = 0; index < mHeaderTitle.size(); index++) {
					TextView txt = new TextView(DispatchContractSelect.this);
					if("发货".equals(mHeaderTitle.get(index))
							||"收货".equals(mHeaderTitle.get(index)) ||
							"单位".equals(mHeaderTitle.get(index)))
					{
						txt.setWidth((int)(mColumnWidth*2.5));
					}
					else if("计划单号".equals(mHeaderTitle.get(index))
							|| "货名".equals(mHeaderTitle.get(index)))
					{
						txt.setWidth((int)(mColumnWidth*1.5));
					}
					else {
						txt.setWidth((int) (mColumnWidth*1.5));
					}

					txt.setTextColor(Color.BLACK);
					txt.setGravity(Gravity.CENTER);
					txt.setCompoundDrawables(mLeftDrawable, null, null, null);
					txt.setPadding(1, 0, 1, 0);
					txt.setId(index);
					txt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
					tableRow.addView(txt);
				}
				tableLayout.addView(tableRow);
				convertView = tableLayout;
				convertView.setTag(tableLayout);
			} else {
				tableLayout = (TableLayout) convertView.getTag();
			}

			JSONObject data = mData.get(position);
			String content;
			for (int index = 0; index < mHeaderTitle.size(); index++) {
				TextView txt = (TextView) tableLayout.findViewById(index);
				if (txt == null)
					continue;
				content = data.optString(mHeaderTitle.get(index));
				if("null".equals(content)) content = "";
				txt.setText(content);
			}
			return convertView;
		}
	}

}
